/*
 * 文 件 名:  GlobalExceptionHandler
 * 版    权:
 * 描    述:  <描述>
 * 修 改 人:  redName
 * 修改时间:  2022/5/6
 * 跟踪单号:  <跟踪单号>
 * 修改单号:  <修改单号>
 * 修改内容:  <修改内容>
 */
package com.zj003.common.exception;

import com.zj003.common.domain.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * <功能详细描述>
 *
 * @author ReaName
 * @version [版本号, 2022/5/6]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {


    @ExceptionHandler(CustomException.class)
    public Result businessException(CustomException e) {
        log.error("自定义异常：----------------{}", e.getMessage(), e);

        if (ObjectUtils.isEmpty(e.getCode())) {
            return Result.error(e.getMessage());
        }
        return Result.error(e.getCode(), e.getMessage());
    }

    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    @ExceptionHandler(value = BadCredentialsException.class)
    public Result handler(BadCredentialsException e) {
        log.error("security未认证：----------------{}", e.getMessage(), e);
        return Result.error("未认证");
    }


    @ResponseStatus(HttpStatus.FORBIDDEN)
    @ExceptionHandler(value = AccessDeniedException.class)
    public Result handler(AccessDeniedException e) {
        log.error("security权限不足：----------------{}", e.getMessage(), e);
        return Result.error("权限不足");
    }

    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(value = RuntimeException.class)
    public Result handler(RuntimeException e) {
        log.error("运行时异常：----------------{}", e.getMessage(), e);
        return Result.error(e.getMessage());
    }

}
